/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-unreachable */
import React from 'react';
import { Modal, Form, Switch, Input, Select, Tree, Row, Col, Radio, Checkbox, Card } from 'antd';
import { 
	getCategoryTree, 
	getComponentData, 
	getDataPermission, 
	getDataTree, 
	getResourcePermission, 
	selectOrgPosWithEmpTree, 
	getPagePermissionByCode, 
	getPageDataPermissionByCode, 
} from 'src/services/AnalyseManage';
import styles from './index.module.scss';
import { mapTreeData, transformTreeData } from 'src/libs/utils';
import { FormInstance } from 'antd/es/form/Form';
import { connect } from 'react-redux';

interface PublishModalProps {
	visible: boolean;
	handleCancel: () => void;
	handleOk: ( form?: any ) => void;
	pageContentConfig: any;
	pageId: string;
	biRoleList: string; //当前用户角色
	reportInfo: any;
	// data: Array<Object>
}

class PublishModal extends React.Component<PublishModalProps> {
	state = {
		isPublic: true,
		isDataAuth: false,
		isPassword: false,
		matchType: 'Manual',
		// 分类
		folderInfo: [],
		folderId: '', //当前选中文件夹id
		// 可见、编辑
		authTreeData: [], // 查询树数据
		editTreeData: [], // 查询编辑树数据
		viewUserList: [], // 发布用
		checkViewList: [], // id打勾
		editUserList: [], // 发布用
		checkEditList: [], // id打勾
		// 图表字段树
		dataAuthList: [],
		tableFieldList: [],
		currentChartKey: '',
		currentTableName: '',
		currentTableField: '',
		// 数据匹配
		fieldValueList: [],
		userTreeData: [],
		selectUser: null,
		selectUserKeys: [],
		manualValueArr: [],
	}

	formRef = React.createRef<FormInstance>();

	// 获取文件夹列表/分类
	getFolderInfo = async () => {
		const res = await getCategoryTree( { type: 'CUSTOMER' } );
		if ( res.data && res.data.success && res.data.data.length ) {
			const folderInfo = res.data.data;
			this.setState( { folderInfo } );
		}
	};

	getAuthTreeData = async ( roleType?: Array<string> ) => {
		const data = {
			type: 'ORGANIZATION',
			roleType
		};
		const res = await selectOrgPosWithEmpTree( data );
		// console.log( res, setAuthTreeData );
		if ( res.data ) {
			const treeData = res.data.data.map( org => mapTreeData( org ) );
			if ( roleType ) {
				this.setState( { editTreeData: treeData } );
			} else {
				this.setState( { authTreeData: treeData } );
			}
		}
	};

	getPagePermission = async () => {
		const data = {
			categoryId: this.state.folderId || this.props.reportInfo.parentId,
			code: this.props.reportInfo.code,
		};
		if ( !data.categoryId ) return;
		const res = await getPagePermissionByCode( data );
		if ( res.data.success ) {
			this.setState( {
				checkViewList: res.data.data.viewUserList,
				checkEditList: res.data.data.editUserList
			} );
			this.formRef.current.setFieldsValue( { 
				viewAuth: res.data.data.viewUserList,
				editAuth: res.data.data.editUserList
			} );
		}
	};

	onCheckViewUser = ( checkedKeys, info ) => {
		// console.log( checkedKeys, info );
		const data = info.checkedNodes.filter( t => t.type === 'USER' ).map( s => s.id );
		this.setState( { viewUserList: data, checkViewList: checkedKeys } );
		this.formRef.current.setFieldsValue( { viewAuth: data } );
		// console.log( data );
	};

	onCheckEditUser = ( checkedKeys, info ) => {
		// console.log( info );
		const data = info.checkedNodes.filter( t => t.type === 'USER' ).map( s => s.id );
		this.setState( { editUserList: data, checkEditList: checkedKeys } );
		this.formRef.current.setFieldsValue( { editAuth: data } );
		// console.log( data );
	};

	// 选择表
	handleChartChange = ( value ) => {
		const { pageContentConfig } = this.props;
		const { children: chartsList } = pageContentConfig;
		const chartItem = chartsList.find( t => t.key === value ) || {};
		const hasTable = this.state.dataAuthList.find( t => t.key === value );
		if ( !hasTable ) {
			const dt = {
				tableName: chartItem.data.tableCode,
				tableField: '',
				componentId: value,
				permissionUserList: [
					{
						fieldValueList: [],
						userId: ''
					}
				],
			};
			const temp = [ ...this.state.dataAuthList, dt ];
			// console.log( temp );
			this.setState( { dataAuthList: temp } );
		}
		this.setState( {
			currentChartKey: value,
			currentTableName: chartItem.data.tableCode,
		} );
		this.getTableFieldList( chartItem.data.tableCode );
	};

	// 获取字段下拉列表
	getTableFieldList = async ( tableCode ) => {
		// const { pageId } = this.props;
		const data = {
			// pageId: pageId,
			isDataResource: 'N',
			modelId: tableCode,
		};
		const res = await getDataTree( data );
		if ( res.data && res.data.data ) {
			// const treeData = res.data.data.map( org => mapTreeData( org ) );
			const tableField = res.data.data[0].children.concat( res.data.data[1].children );
			this.setState( {
				tableFieldList: tableField
			}, () => {
			} );
			// console.log( fieldData );
		}
	};

	// 选择字段
	handleTableFiledChange = ( value ) => {
		let needPush = true; // 有空就填充，无空就push
		const { dataAuthList, currentChartKey, currentTableName } = this.state;
		let temp = dataAuthList.map( t => {
			if ( t.componentId === currentChartKey && t.tableName === currentTableName ) {
				if ( t.tableField === '' || t.tableField === value ) {
					needPush = false;
					return {
						...t,
						tableField: value
					};
				} else {
					return t;
				}
			} else {
				return t;
			}
		} );
		if ( needPush ) {
			const dt = {
				tableName: currentTableName,
				tableField: value,
				componentId: currentChartKey,
				permissionUserList: [
					{
						fieldValueList: [],
						userId: ''
					}
				],
			};
			temp = [ ...dataAuthList, dt ];
		}
		// console.log( temp );
		this.setState( {
			dataAuthList: temp,
			currentTableField: value,
		} );
		this.getFiledValueList( value );
	};

	// 获取手动匹配列表数据
	getFiledValueList = async ( tableField ) => {
		const { tableFieldList, currentTableName } = this.state;
		const { pageId } = this.props;
		const filedItem = tableFieldList.find( t => t.name === tableField );
		// console.log( filedItem, filedName );
		const request = {
			type: 'filter',
			dataConfig: {
				// tableAggregate: this.props.config.data.openAggregation || false,
				dataModel: {
					pageId: pageId,
					// tableName: 'ORDERS_USCA_BI',
					tableName: currentTableName,
					x: [ {
						id: filedItem.name,
						alias: filedItem.aliasName,
						dataType: filedItem.dataType,
						quota: filedItem.isMensure === 'N' ? 'WD' : 'DL',
						type: filedItem.type,
					} ],
				},
				tableType: 'base',
			},
		};
		const res = await getComponentData( request );
		if ( res.data.data ) {
			this.setState( {
				fieldValueList: res.data.data.rows
			} );
		}
	};

	// 匹配方式
	handleMatchChange = ( e ) => {
		// console.log( e );
		this.setState( {
			// dataAuthList: [],
			matchType: e.target.value
		}, () => {
			this.getUserTreeData( e.target.value );
		} );
	};

	// 自动匹配
	handleAutoMatch = ( treeData ) => {
		let tempUserList = transformTreeData( [], treeData ); // 平级UserList
		const { dataAuthList, currentChartKey, currentTableName, currentTableField, fieldValueList, matchType } = this.state;
		let requestData = [];
		// fieldValueList：字段选择对应的value数据，tempUserList：平级结构的人员数据
		let tempDataAuthList = JSON.parse( JSON.stringify( dataAuthList ) );
		// console.log( fieldValueList, tempUserList );
		fieldValueList.forEach( v => {
			const pickUser = tempUserList.find( t => t.name === v.value ); // 1对1匹配上
			if ( pickUser ) {
				const valueList = tempUserList.filter(
					g => g.type === 'USER' &&
						matchType === 'USER' ? g.id === pickUser.id : g.parentId === pickUser.id )
					.map( t => t.name );
				// console.log( tempDataAuthList, currentChartKey, currentTableName, currentTableField );
				let needPush = true; // 有空就填充，无空就push
				requestData = tempDataAuthList.map( t => {
					if ( t.componentId === currentChartKey
						&& t.tableName === currentTableName
						&& t.tableField === currentTableField ) {
						let tempPermissionUserList = t.permissionUserList.map( s => {
							if ( s.userId === '' || s.userId === pickUser.id ) {
								needPush = false;
								return {
									fieldValueList: valueList,
									userId: pickUser.id
								};
							} else {
								return s;
							}
						} );
						if ( needPush ) {
							tempPermissionUserList = [ ...tempPermissionUserList, {
								fieldValueList: valueList,
								userId: pickUser.id
							} ];
						}
						return {
							...t,
							permissionUserList: tempPermissionUserList
						};
					} else {
						return t;
					}
				} );
				tempDataAuthList = requestData;
			}
		} );
		this.setState( {
			dataAuthList: requestData
		} );
		// console.log( requestData );
	};

	getUserTreeData = async ( type ) => {
		const data = {
			type: type === 'Manual' ? 'ORGANIZATION' : type
		};
		const res = await selectOrgPosWithEmpTree( data );
		if ( res.data ) {
			let treeData = res.data.data.map( org => mapTreeData( org ) );
			// console.log( res.data.data, treeData );
			this.setState( {
				userTreeData: treeData
			}, () => {
				if ( type !== 'Manual' ) {
					this.handleAutoMatch( treeData );
				}
			} );
		}
	};

	onSelectUser = ( selectedKeys, e: { selected: boolean, selectedNodes, node, event } ) => {
		const { dataAuthList, currentChartKey, currentTableName, currentTableField } = this.state;
		// console.log( selectedKeys, e );
		// if ( !e.selected ) {
		// 	this.setState( {
		// 		manualValueArr: []
		// 	} );
		// }
		this.setState( {
			selectUser: e.selected ? e.node : null
		} );

		const temp = dataAuthList.map( t => {
			if ( t.tableName === currentTableName &&
				t.tableField === currentTableField &&
				t.componentId === currentChartKey ) {
				const user = t.permissionUserList.find( s => s.userId === e.node.id );
				if ( user ) {
					this.setState( {
						manualValueArr: user.fieldValueList
					} );
				} else {
					this.setState( {
						manualValueArr: []
					} );
				}
				return {
					...t,
					permissionUserList: e.selected ? t.permissionUserList : t.permissionUserList.filter( t => t.userId !== e.node.id )
				};
			} else {
				return t;
			}
		} );
		if ( !e.selected ) {
			this.setState( {
				dataAuthList: temp,
				manualValueArr: []
			} );
		}
		// console.log( dataAuthList, e.node, this.state.manualValueArr );
		// form.setFieldsValue( { checkUser: data } );
	};

	// 手动匹配
	handleManualCheck = ( value ) => {
		const { dataAuthList, currentChartKey, currentTableName, currentTableField, selectUser } = this.state;
		// console.log( dataAuthList, value );
		let needPush = true; // 有空就填充，无空就push
		let temp = dataAuthList.map( t => {
			if ( t.componentId === currentChartKey
				&& t.tableName === currentTableName
				&& t.tableField === currentTableField ) {
				let tempPermissionUserList = t.permissionUserList.map( s => {
					if ( s.userId === '' || s.userId === selectUser.id ) {
						needPush = false;
						return {
							fieldValueList: value,
							userId: selectUser.id
						};
					} else {
						return s;
					}
				} );
				if ( needPush ) {
					tempPermissionUserList = [ ...tempPermissionUserList, {
						fieldValueList: value,
						userId: selectUser.id
					} ];
				}
				// console.log( tempPermissionUserList );
				return {
					...t,
					permissionUserList: tempPermissionUserList
				};
			} else {
				return t;
			}
		} );
		this.setState( {
			dataAuthList: temp,
			manualValueArr: value
		} );
	};

	getDataPermission = async () => {
		const data = {
			pageId: this.props.pageId
		};
		const res = await getDataPermission( data );
		// eslint-disable-next-line @typescript-eslint/no-unused-vars
		if ( !res.data.data ) {
			return;
		}
		const { componentId, tableField, tableName, permissionUserList } = res.data.data[0];
		await this.getTableFieldList( tableName );
		this.setState( {
			currentChartKey: componentId,
			currentTableField: tableField,
			currentTableName: tableName,
			dataAuthList: res.data.data,
			selectUserKeys: permissionUserList[0].userId,
			manualValueArr: permissionUserList[0].fieldValueList
		}, () => {
			this.getFiledValueList( tableField );
			this.formRef.current.setFieldsValue( { componentId, tableField, tableName } );
			console.log( this.state.selectUserKeys );
		} );
	}
	getPageDataPermission = async () => {
		const data = {
			categoryId: this.state.folderId || this.props.reportInfo.parentId,
			code: this.props.reportInfo.code,
		};
		if ( !data.categoryId ) return;
		const res = await getPageDataPermissionByCode( data );
		// eslint-disable-next-line @typescript-eslint/no-unused-vars
		if ( !res.data.data ) {
			return;
		}
		const { componentId, tableField, tableName, permissionUserList } = res.data.data[0];
		await this.getTableFieldList( tableName );
		this.setState( {
			currentChartKey: componentId,
			currentTableField: tableField,
			currentTableName: tableName,
			dataAuthList: res.data.data,
			selectUserKeys: permissionUserList[0].userId,
			manualValueArr: permissionUserList[0].fieldValueList
		}, () => {
			this.getFiledValueList( tableField );
			this.formRef.current.setFieldsValue( { componentId, tableField, tableName } );
			console.log( this.state.selectUserKeys );
		} );
	};

	getPermission = async () => {
		const data = {
			id: this.props.pageId,
			resourceType: 'page'
		};
		const res = await getResourcePermission( data );
		if ( res.data ) {
			this.setState( {
				checkViewList: res.data.data.viewUserList,
				checkEditList: res.data.data.editUserList
			} );
			this.formRef.current.setFieldsValue( { viewAuth: res.data.data.viewUserList, editAuth: res.data.data.editUserList } );
			// setCheckTreeData()
			// console.log( res.data.data.viewUserList, res.data.data.editUserList );
		}
	};

	componentDidMount() {
	}

	shouldComponentUpdate( nextProps: Readonly<PublishModalProps>, nextState: Readonly<{ dependencies: any }>, nextContext: any ): boolean {
		// console.log( nextProps, this.props, nextState, this.state );
		if ( JSON.stringify( nextProps ) !== JSON.stringify( this.props ) ||
			JSON.stringify( nextState ) !== JSON.stringify( this.state ) ) return true;
		return false;
	}

	getSnapshotBeforeUpdate( prevProps: Readonly<PublishModalProps>, prevState: Readonly<{ dependencies: any }> ): any | null {
		let changeObj = Object.create( null );
		if ( prevProps.visible !== this.props.visible && !!this.props.visible ) {
			changeObj.needGetData = true;
		}
		return changeObj;
	}

	async componentDidUpdate( prevProps: Readonly<PublishModalProps>, prevState: Readonly<{}>, snapshot?: any ) {
		const deloitteFlag = this.props.pageContentConfig.page.deloitteFlag;
		if ( snapshot.needGetData && deloitteFlag !== '1' ) {
			// console.log( this.props.pageContentConfig.page.parentId );
			if ( this.props.reportInfo.isPublic === '0' ) {
				this.setState( {
					isPublic: false
				} );
			}
			if ( this.state.matchType === 'Manual' ) {
				this.getUserTreeData( 'Manual' );
			}
			this.formRef.current.setFieldsValue( { 'categoryId': this.state.folderId || this.props.reportInfo.parentId } );
			this.getFolderInfo();
			this.getAuthTreeData();
			this.getAuthTreeData( [ 'editor' ] );
			// this.getDataPermission();
			// this.getPermission();
			this.getPageDataPermission();
			this.getPagePermission();
		}
	}

	componentWillUnmount() {
		// this.formRef.current.resetFields();
	}

	handlePublish = () => {
		const deloitteFlag = this.props.pageContentConfig.page.deloitteFlag;
		// 从德勤方案创建的报表
		if ( deloitteFlag === '1' ) {
			const data = {
				deloitteFlag,
			};
			this.props.handleOk( data );
			this.resetState();
			return;
		}
		// console.log( id, editUserList, viewUserList );
		const { viewUserList, editUserList, isPublic } = this.state;
		const { password, categoryId } = this.formRef.current.getFieldsValue();
		console.log( this.formRef.current.getFieldsValue() );
		const permissionItemDtoList = this.state.dataAuthList.map( t => {
			const permissionUserList = t.permissionUserList.filter( s => s.userId !== '' && s.fieldValueList.length );
			if ( !permissionUserList.length ) {
				return null;
			} else {
				return {
					...t,
					permissionUserList
				};
			}
		} ).filter( w => !!w );
		// console.log( permissionItemDtoList );
		const data = {
			deloitteFlag: deloitteFlag || '0',
			permissionItemDtoList,
			saveResourcePermissionDto: {
				editUserList,
				id: this.props.pageId,
				resourceType: 'page',
				viewUserList
			},
			isPublic,
			password,
			categoryId
		};
		// console.log( data,  this.formRef.current.getFieldsValue() );
		this.props.handleOk( data );
		this.resetState();
	};

	resetState = () => {
		this.setState( {
			isPublic: true,
			isDataAuth: true,
			isPassword: false,
			matchType: 'Manual',
			// 分类
			folderInfo: [],
			// 可见、编辑
			authTreeData: [],
			editTreeData: [],
			viewUserList: [],
			editUserList: [],
			// 图表字段树
			dataAuthList: [],
			tableFieldList: [],
			currentChartKey: '',
			currentTableName: '',
			currentTableField: '',
			// 数据匹配
			fieldValueList: [],
			userTreeData: [],
			selectUser: null
		} );
	}

	onCancel = () => {
		if ( this.props.pageContentConfig.page.deloitteFlag !== '1' ) {
			this.formRef.current.resetFields();
		}
		this.resetState();
		this.props.handleCancel();
	}

	changeFolder = ( value ) => {
		this.setState( { folderId: value }, () => {
			this.getPageDataPermission();
			this.getPagePermission();
		} );
	}

	render() {
		let { isPublic, folderInfo, authTreeData, editTreeData, isDataAuth, tableFieldList, userTreeData,
			fieldValueList, isPassword, manualValueArr, checkViewList, checkEditList, selectUserKeys } = this.state;
		const { visible, pageContentConfig } = this.props;
		const { children: chartsList, page: pageInfo } = pageContentConfig;

		const { Option } = Select;
		return (
			<>
				<Modal
					title="发布报表"
					visible={visible}
					width="850px"
					onCancel={this.onCancel}
					onOk={this.handlePublish}
					okText="确定"
					cancelText="取消"
					className={styles.analysis_publishmodal}
				>
					<div>
						{
							pageInfo.deloitteFlag === '1' ? (
								<p>确定要发布该报表吗？</p>
							) : (
								<Form
									initialValues={{ classify: pageInfo.parentId }}
									labelCol={{ span: 3 }}
									layout="horizontal"
									ref={this.formRef}
								>
									<Form.Item label="选择分类" name="categoryId" rules={ [ { required: true, message: '不能为空！' } ] }>
										<Select onChange={this.changeFolder}
											style={{ width: 200 }}>
											{
												folderInfo.map( t =>
													<Option value={t.id} key={t.id}>{t.name}</Option>
												)
											}
										</Select>
									</Form.Item>
									<Form.Item label="公开报表" name="isPublic">
										<Switch checked={isPublic} onChange={( checked ) => this.setState( { isPublic: checked } )} />
									</Form.Item>
									{!isPublic &&
											<>
												<Form.Item label="可见权限" name="viewAuth">
													<Card style={{ width: 300 }}>
														<Tree
															checkable
															treeData={authTreeData}
															checkedKeys={checkViewList}
															onCheck={this.onCheckViewUser}
														/>
													</Card>
												</Form.Item>
												<Form.Item label="编辑权限" name="editAuth">
													<Card style={{ width: 300 }}>
														<Tree
															checkable
															treeData={editTreeData}
															checkedKeys={checkEditList}
															onCheck={this.onCheckEditUser}
														/>
													</Card>
												</Form.Item>
											</>
									}
									{!isPublic && <Form.Item label="启用数据权限" name="isOpenDataAuth">
										<Switch checked={isDataAuth} onChange={( checked ) => this.setState( { isDataAuth: checked } )} />
									</Form.Item>}
									{
										!isPublic && isDataAuth &&
											<>
												<Form.Item label="图表选择" name="componentId">
													<Select style={{ width: 200 }} onChange={this.handleChartChange}>
														{
															chartsList.map( t =>
																<Option value={t.key} key={t.key}>{t.style.titleValue}</Option>
															)
														}
													</Select>
												</Form.Item>
												<Form.Item label="字段选择" name="tableField">
													<Select style={{ width: 200 }} onChange={this.handleTableFiledChange}>
														{
															tableFieldList.map( t =>
																<Option value={t.name} key={t.id}>{t.desc || t.name}</Option>
															)
														}
													</Select>
												</Form.Item>
												<Form.Item label="人员" name="userId">
													<Row gutter={48}>
														<Col span={12}>
															<Card style={{ width: 300 }}>
																<Tree
																	defaultExpandAll
																	treeData={userTreeData}
																	onSelect={this.onSelectUser}
																/>
															</Card>
														</Col>
														<Col span={12}>
															<div>
																<div>匹配方式选择</div>
																<Radio.Group value={this.state.matchType} onChange={this.handleMatchChange}>
																	<Radio value='ORGANIZATION'>组织</Radio>
																	<Radio value='POSITION'>岗位</Radio>
																	<Radio value='USER'>人员</Radio>
																	<Radio value='Manual'>手动</Radio>
																</Radio.Group>
															</div>
															<div className={styles.manual_container}>
																<div>手动匹配</div>
																<Card style={{ width: 300 }}>
																	<Checkbox.Group disabled={this.state.matchType !== 'Manual' || !this.state.selectUser} style={{ width: '100%' }}
																		value={manualValueArr} onChange={this.handleManualCheck}>
																		<Row>
																			{
																				fieldValueList.map( t => (
																					<Col key={t.value} span={24}>
																						<Checkbox value={t.value}>{t.value}</Checkbox>
																					</Col>
																				) )
																			}
																		</Row>
																	</Checkbox.Group>
																</Card>
															</div>
														</Col>
													</Row>
												</Form.Item>
											</>
									}
									{isPublic && <Form.Item label="是否加密" name="layout">
										<Switch checked={isPassword} onChange={( checked ) => this.setState( { isPassword: checked } )} />
									</Form.Item>}
									{isPassword && isPublic && (
										<Form.Item label="密码" name="password">
											<Input.Password style={{ width: '300px' }} />
										</Form.Item>
									)}
									{/* <Form.Item label="报表链接" name="link">
										<Input.Group compact>
											<Input id="publish_copy" addonBefore="http://" style={{ width: '80%' }} />
											<Button onClick={() => copyTranslateResult( '#publish_copy' )} type="primary" style={{ width: '15%' }}>复制</Button>
										</Input.Group>
									</Form.Item> */}
								</Form>
							)
						}
					</div>
				</Modal>
			</>
		);
	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		biRoleList: state.user.biRoleTypeList || '',
	};
};

export default connect(
	mapStateToProps,
)( PublishModal );
